<template>
  <div style="height: 100%; width: 100%">
    <!-- 查询框 -->
    <div>
      <el-select v-model="searchType" placeholder="请选择查询条件" style="width: 150px;">
        <el-option label="序号" value="id"></el-option>
        <el-option label="姓名" value="name"></el-option>
      </el-select>
      <el-input v-model="keyword" style="width: 300px; margin-left: 10px; margin-right: 10px" placeholder="请输入关键词"></el-input>
      <el-button type="primary" @click="search">查询</el-button>
      <el-button type="info" @click="reset">重置</el-button>
    </div>

    <!-- 表格 -->
    <div style="margin: 10px 0">
      <el-table :data="appointments" stripe :header-cell-style="{ backgroundColor: 'aliceblue', color: '#666' }"
                @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <el-table-column prop="id" label="序号" width="70" align="center"></el-table-column>
        <el-table-column prop="patient_name" label="患者姓名"></el-table-column>
        <el-table-column prop="appointment_date" label="预约日期"></el-table-column>
        <el-table-column prop="appointment_time" label="预约时间"></el-table-column>
        <el-table-column prop="appointment_purpose" label="预约目的"></el-table-column>
        <el-table-column prop="status" label="状态"></el-table-column>
        <el-table-column label="操作" align="center" width="180">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" plain @click="handleEdit(scope.row)">治疗</el-button>
            <el-button size="mini" type="danger" plain @click="handleDelete(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页组件 -->
    <div style="margin-top: 20px; text-align: center;">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5, 10, 20, 50]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalItems">
        <!--实现分页功能的，通过分页组件可以让用户方便地切换不同的页码和调整每页显示的条目数量，从而更好地浏览大量数据-->
      </el-pagination>
      <!-- 治疗弹窗 -->
      <el-dialog :title="title" :visible.sync="dialogVisible" width="30%">
        <el-steps :active="activeStep">
          <el-step title="预约信息"></el-step>
          <el-step title="治疗计划"></el-step>
          <el-step title="治疗清单"></el-step>
        </el-steps>
        <el-form ref="form" :model="editItem" label-width="80px">
          <!-- 步骤一 -->
          <div v-show="activeStep === 0">
            <el-form-item label="患者姓名" prop="patient_name">
              <el-input v-model="editItem.patient_name"></el-input>
            </el-form-item>
            <el-form-item label="预约目的" prop="appointment_purpose">
              <el-input v-model="editItem.appointment_purpose"></el-input>
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-input v-model="editItem.status"></el-input>
            </el-form-item>
            <el-form-item label="医生姓名" prop="doctor_name">
              <el-input v-model="editItem.doctor_name"></el-input>
            </el-form-item>
          </div>

          <!-- 步骤二 -->
          <div v-show="activeStep === 1">
            <el-form-item label="治疗日期" prop="treatment_date">
              <el-date-picker v-model="editItem.treatment_date" type="date" placeholder="选择日期" value-format="yyyy-MM-dd"></el-date-picker>
            </el-form-item>
            <el-form-item label="治疗方案" prop="treatment_content">
              <el-checkbox-group v-model="selectedTreatmentPlans">
                <el-checkbox v-for="plan in treatmentPlans" :key="plan.id" :label="plan">
                  {{ plan.treatment_content }}
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            <div v-for="(plan, index) in selectedTreatmentPlans" :key="index" style="margin-top: 10px;">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="金额">
                    <el-input v-model="plan.treatment_free" readonly></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
            <el-form-item label="治疗用品" prop="treatment_inventory">
              <el-checkbox-group v-model="selectedInventoryItems">
                <el-checkbox v-for="item in inventoryItems" :key="item.id" :label="item">
                  {{ item.product_name }}{{ item.inventoryQuantity  }}
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            <div v-for="(item, index) in selectedInventoryItems" :key="index" style="margin-top: 10px;">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item :label="item.product_name">
                    <el-input-number v-model="item.quantity" size="small" :min="1" @change="calculateFee"></el-input-number>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="金额">
                    <el-input v-model="item.amount" readonly></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
            <el-form-item label="总金额" prop="treatment_fee">
              <el-input v-model="editItem.treatment_fee" readonly></el-input>
            </el-form-item>
          </div>



          <!-- 步骤三 -->
          <div v-show="activeStep === 2">
            <div>患者姓名：{{ editItem.patient_name }}</div>
            <div>预约目的：{{ editItem.appointment_purpose }}</div>
            <div>状态：{{ editItem.status }}</div>
            <div>医生姓名：{{ editItem.doctor_name }}</div>
            <div>治疗日期：{{ editItem.treatment_date }}</div>
            <div>治疗方案：</div>
            <ul>
              <li v-for="plan in selectedTreatmentPlans" :key="plan.id">
                {{ plan.treatment_content }} -- 金额：{{ plan.treatment_free }}
              </li>
            </ul>
            <div>治疗用品清单：</div>
            <ul>
              <li v-for="item in selectedInventoryItems" :key="item.id">
                {{ item.product_name }} -- 数量：{{ item.quantity }} -- 金额：{{ item.amount }}
              </li>
            </ul>
            <div>总金额：{{ editItem.treatment_fee }}</div>
          </div>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button v-show="activeStep > 0" @click="prevStep">上一步</el-button>
          <el-button v-show="activeStep < 2" type="primary" @click="nextStep">下一步</el-button>
          <el-button v-show="activeStep === 2" type="primary" @click="handleSaveEdit">保存</el-button>
          <el-button @click="closeDialog">取消</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import axios from 'axios';

export default {
  name: 'TreatmentPlan',
  data() {
    return {
      appointments: [],
      treatments: [],
      inventoryItems: [],
      selectedInventoryItems: [],
      treatmentPlans: [],
      selectedTreatmentPlans: [],
      selectedRows: [],
      currentPage: 1,//当前页数
      pageSize: 5,
      totalItems: 0,//总条数
      searchType: 'id',
      keyword: '',
      title: '治疗方案',
      dialogVisible: false,
      editItem: {
        patient_name: '',
        appointment_purpose: '',
        status: '',
        doctor_name: '',
        treatment_date: '',
        treatment_content: '',
        treatment_fee: '',
      },
      activeStep: 0,//步骤条当前步骤
    };
  },

  mounted() {
    this.search();//按条件查询
    this.loadInventoryItems(); // 加载库存物品
    this.loadTreatmentPlans()//加载治疗方案
  },
  methods: {
    loadTreatmentPlans() {
      axios.get('http://localhost:8080/treatment_plans/selectAll')
          .then(response => {
            this.treatmentPlans = response.data.data;
          })
          .catch(error => {
            console.error('Error fetching treatment plans:', error);
          });
    },

    loadInventoryItems() {
      axios.get('http://localhost:8080/Inventory/selectAll1')
          .then(response => {
            this.inventoryItems = response.data.data.map((item, index) => ({
              ...item,
              inventoryQuantity: item.quantity,
              id: index // 确保有唯一的 id
            }));
          })
          .catch(error => {
            console.error('Error fetching inventory items:', error);
          });
    },
    search() {
      let url = 'http://localhost:8080/appointments/selectAll';
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        status: '待治疗'
      };

      if (this.keyword) {
        url = `http://localhost:8080/appointments/selectBy${this.searchType}?${this.searchType}=${this.keyword}`;
      }

      axios.get(url, {params})
          .then(response => {
            const data = response.data.data;
            this.appointments = data.list.filter(appointment => appointment.status === '待治疗');
            this.totalItems = data.total;//记录获取的数量
          })
          .catch(error => {
            console.error('Error fetching appointments:', error);
          });
    },
    reset() {
      this.searchType = 'id';
      this.keyword = '';
      this.currentPage = 1;
      this.pageSize = 5;
      this.search();
    },
    handleSizeChange(size) {
      this.pageSize = size;
      this.search();
    },
    handleCurrentChange(page) {
      this.currentPage = page;
      this.search();
    },
    handleSelectionChange(val) {
      this.selectedRows = val.map(row => row.id);//提取选中的id
    },
    closeDialog() {
      this.dialogVisible = false;
      this.isEditing = false;
    },
    handleEdit(row) {
      this.editItem = Object.assign({}, row);
      this.selectedInventoryItems = [];
      this.dialogVisible = true;
    },
    handleSaveEdit() {
      const treatmentData = {//声明常量
        patient_name: this.editItem.patient_name,
        appointment_purpose: this.editItem.appointment_purpose,
        status: "已治疗",
        doctor_name: this.editItem.doctor_name,
        treatment_date: this.editItem.treatment_date,
        treatment_content:JSON.stringify(this.selectedTreatmentPlans.map(plan => ({
          治疗方案:plan.treatment_content,
          治疗金额:plan.treatment_free,
        }))),
        treatment_product:JSON.stringify(this.selectedInventoryItems.map(item => ({
          治疗用具名称: item.product_name,
          治疗用具数量: item.quantity,
          治疗用具金额: item.amount,
        }))),
        treatment_fee: this.editItem.treatment_fee,
      };

      const finacailData = {//财务记录
        name: JSON.stringify(this.selectedTreatmentPlans.map(plan => ({
          治疗方案:plan.treatment_content ,
          治疗金额:plan.treatment_free,
        }))),
        amount: this.editItem.treatment_fee,
        date: this.editItem.treatment_date,
        type: "收入",
        remark: JSON.stringify(this.selectedInventoryItems.map(item => ({
          号: item.id,
          名: item.product_name,
          数量: item.quantity,
          金额: item.amount,
        }))),
      };



      console.log(treatmentData)
      console.log(finacailData)






      axios.post('http://localhost:8080/treatments/add', treatmentData)//发送post请求
          .then(response => {
            this.$message.success("治疗信息保存成功");
            this.closeDialog();

            // 更新库存数量
            this.selectedInventoryItems.forEach(item => {
              const updatedInventory = {
                id: item.id,
                quantity: item.inventoryQuantity - item.quantity
              };
              axios.put(`http://localhost:8080/Inventory/update/${item.id}`, updatedInventory)
                  .then(response => {
                    console.log('库存更新成功');
                  })
                  .catch(error => {
                    console.error('Error updating inventory:', error);
                    this.$message.error('库存更新失败');
                  });
            });

            //插入财务
            axios.post('http://localhost:8080/finances/add', finacailData)
                .then(response => {
                  console.log("财务插入成功");
                })
                .catch(error => {
                  console.error('Error add finances:', error);
                  this.$message.error('财务插入失败');
                })

            axios.put(`http://localhost:8080/appointments/updateStatus/${this.editItem.id}`, {status: '已治疗'})
                .then(response => {
                  this.$message.success("预约记录更新成功");
                  this.search();
                })
                .catch(error => {
                  console.error('Error updating appointment status:', error);
                  this.$message.error("预约记录更新失败");
                });
          })
          .catch(error => {
            console.error('Error saving treatment:', error);
            this.$message.error("治疗信息保存失败");
          });
    },
    handleDelete(id) {
      this.$confirm('此操作将永久删除该条目，是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios.delete(`http://localhost:8080/appointments/delete/${id}`)
            .then(response => {
              this.$message.success('删除成功');
              this.search();
            })
            .catch(error => {
              console.error('Error deleting item:', error);
              this.$message.error('删除失败');
            });
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    nextStep() {
      this.activeStep += 1;
    },
    prevStep() {
      this.activeStep -= 1;
    },
    calculateFee() {
      let totalFee = 0;
      this.selectedInventoryItems.forEach(item => {
        item.amount = item.price * item.quantity;
        totalFee += item.amount;
      });
      this.selectedTreatmentPlans.forEach(plan => {
        totalFee += parseFloat(plan.treatment_free);// 确保金额是浮点数
      });
      this.editItem.treatment_fee = totalFee.toFixed(2);
    }
  },

    watch: {//被调用来重新计算费用
    'selectedInventoryItems': {
      handler: 'calculateFee',
      deep: true
    },
    'selectedTreatmentPlans': {
      handler: 'calculateFee',
      deep: true
    }
  }
};
</script>
<style scoped>
.dialog-footer {
  text-align: right;
}
</style>